import { BrowserWindow, ipcMain, dialog } from 'electron'
// import { is } from '@electron-toolkit/utils'
import { statSync } from 'fs'
import { basename, extname, dirname, join } from 'path'
import pdf from 'pdf-poppler'
import { PythonShell } from 'python-shell'
// import PDFJS from 'pdfjs-dist'

/** 设置窗口标题 */
const setTitle = () => {
  return ipcMain.on('set-title', (event, title) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win?.setTitle(title)
  })
}

/** 选择文件夹 */
const openDirectory = () => {
  return ipcMain.handle('dialog:openDirectory', async () => {
    try {
      const { canceled, filePaths } = await dialog.showOpenDialog({ properties: ['openDirectory'] })
      return {
        canceled: canceled,
        filePaths: filePaths,
        code: 'success',
        msg: 'success'
      }
    } catch (error) {
      return {
        code: 'error',
        msg: error,
        filePaths: []
      }
    }
  })
}

/** 选择文件 */
const chooseFiles = () => {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  return ipcMain.handle('choose-files', async (event, values = {}) => {
    const defaultConfig = {
      properties: ['openFile', 'multiSelections'],
      filters: [{ name: 'Pdf文件', extensions: ['pdf'] }]
    }
    const object = Object.assign({}, defaultConfig, values)
    try {
      const { canceled, filePaths } = await dialog.showOpenDialog(object)
      const files: any[] = []
      if (filePaths.length > 0) {
        filePaths.forEach(async (item) => {
          const file = statSync(item)
          files.push({
            ...file,
            fileName: basename(item),
            filePath: item,
            fileId: `${basename(item)}-${file.ino}-${file.size}`
          })
        })
      }
      console.log('选择的文件：', files)
      return {
        canceled: canceled,
        files: files,
        code: 'success',
        msg: 'success'
      }
    } catch (error) {
      return {
        code: 'error',
        msg: error,
        files: []
      }
    }
  })
}

/** 获取存储值 */
const getStoreValue = (store): any => {
  return ipcMain.handle('store:getStoreValue', (_event, key) => {
    console.log('///getStoreValue///', key)
    return store.get(key)
  })
}

/** 设置单个存储值 */
const setStoreValue = (store) => {
  return ipcMain.handle('store:setStoreValue', (_event, key, value) => {
    console.log('///setStoreValue///', key, value)
    return store.set(key, value)
  })
}

/** 设置多个存储值 */
const setStoreValues = (store) => {
  return ipcMain.handle('store:setStoreValues', (_event, values) => {
    console.log('///setStoreValues///', values)
    return store.set(values)
  })
}

/** 是否有某个存储值 */
const hasStoreValue = (store) => {
  return ipcMain.handle('store:hasStoreValue', (_event, key) => {
    return store.has(key)
  })
}

/** 删除存储值 */
const deleteStoreValue = (store) => {
  return ipcMain.handle('store:deleteStoreValue', (_event, key) => {
    return store.delete(key)
  })
}

/** 删除所有存储值 */
const deleteAllStoreValue = (store) => {
  return ipcMain.handle('store:deleteAllStoreValue', () => {
    return store.clear()
  })
}

/** pdf 转换图片 */
const pdfToImg = (store) => {
  return ipcMain.handle('convert:pdfToImg', (_event, files = []) => {
    console.log(files)

    // 输出目录
    const outputManage = store.get('outputManage')
    const { outputPath, equalSource } = outputManage

    return new Promise((resolve) => {
      async function pdfToImage (savePath, fileItem) {
        const { filePath, fileId } = fileItem

        try {
          const opts = {
            // 格式
            format: 'jpeg',
            // 图片宽度
            scale: 1042,
            // 输出目录, dirname(filePath), savePath
            out_dir: equalSource ? dirname(filePath) : savePath,
            // 文件名
            out_prefix: basename(filePath, extname(filePath)),
            page: null
          }

          await pdf.convert(filePath, opts)

          return Promise.resolve({
            fileId,
            success: true
          })
        } catch (error) {
          console.log(error)
        }
        return
      }

      // 等待所有异步操作完成再统一返回
      Promise.all(
        files.map((item) => {
          return new Promise(async (resolve) => {
            // const pdfFile = readFileSync(item.filePath)
            const result = await pdfToImage(outputPath, item).catch((err) =>
              console.log('***err', err)
            )
            resolve(result)
          })
        })
      ).then((res) => {
        resolve(res)
      })
    })
  })
}

/** pdf 转换为word */
const pdfToWord = (store) => {
  return ipcMain.handle('convert:pdfToWord', (_event, files = []) => {
    console.log(files)

    return new Promise(async (pResolve) => {
      const outputManage = store.get('outputManage')
      console.log(outputManage)
      let options = {}
      // let pyshell = new PythonShell('pdfToWord.py', options)
      options = {
        scriptPath: join(process.cwd(), '/python_scripts'), // process.cwd()：读取 当前nodejs程序的根目录
        pythonPath: join(process.cwd(), '/python-3.10.10-embed-win32/python'),
        // pythonOptions: ['-u'], // get print results in real-time
        args: [
          `-filePath=${JSON.stringify(files)}`,
          `-outputManage=${JSON.stringify(outputManage)}`
        ],
        mode: 'text'
      }

      PythonShell.run('pdfToWord.py', options)
        .then((result) => {
          console.log('result: ', result.toString())
          const resultArr = result.toString().split(',')
          console.log(resultArr)
          const returnArr: { fileId: string; success: boolean }[] = []
          resultArr.map((item) => {
            returnArr.push({
              fileId: item,
              success: true
            })
          })
          pResolve(returnArr)
        })
        .catch((error) => console.log(error))
    })
  })
}
/** ppt 转换为pdf */
const pptToPdf = (store) => {
  return ipcMain.handle('convert:pptToPdf', (_event, files = []) => {
    console.log(files)

    return new Promise(async (pResolve) => {
      const outputManage = store.get('outputManage')
      console.log(outputManage)
      let options = {}
      options = {
        scriptPath: join(process.cwd(), '/python_scripts'), // process.cwd()：读取 当前nodejs程序的根目录
        pythonPath: join(process.cwd(), '/python-3.10.10-embed-win32/python'),
        // pythonOptions: ['-u'], // get print results in real-time
        args: [
          `-filePath=${JSON.stringify(files)}`,
          `-outputManage=${JSON.stringify(outputManage)}`
        ],
        mode: 'text'
      }

      PythonShell.run('pptToPdf.py', options)
        .then((result) => {
          console.log('result---: ', result.toString())
          const resultArr = result.toString().split(',')
          console.log(resultArr)
          const returnArr: { fileId: string; success: boolean }[] = []
          resultArr.map((item) => {
            returnArr.push({
              fileId: item,
              success: true
            })
          })
          pResolve(returnArr)
        })
        .catch((error) => console.log(error))
    })
  })
}
/** word 转换为pdf */
const wordToPdf = (store) => {
  return ipcMain.handle('convert:wordToPdf', (_event, files = []) => {
    console.log(files)

    return new Promise(async (pResolve) => {
      const outputManage = store.get('outputManage')
      console.log(outputManage)
      let options = {}
      options = {
        scriptPath: join(process.cwd(), '/python_scripts'), // process.cwd()：读取 当前nodejs程序的根目录
        pythonPath: join(process.cwd(), '/python-3.10.10-embed-win32/python'),
        // pythonOptions: ['-u'], // get print results in real-time
        args: [
          `-filePath=${JSON.stringify(files)}`,
          `-outputManage=${JSON.stringify(outputManage)}`
        ],
        mode: 'text'
      }

      PythonShell.run('wordToPdf.py', options)
        .then((result) => {
          console.log('result---: ', result.toString())
          const resultArr = result.toString().split(',')
          console.log(resultArr)
          const returnArr: { fileId: string; success: boolean }[] = []
          resultArr.map((item) => {
            returnArr.push({
              fileId: item,
              success: true
            })
          })
          pResolve(returnArr)
        })
        .catch((error) => console.log(error))
    })
  })
}
/** excel 转换为pdf */
const excelToPdf = (store) => {
  return ipcMain.handle('convert:excelToPdf', (_event, files = []) => {
    console.log(files)

    return new Promise(async (pResolve) => {
      const outputManage = store.get('outputManage')
      console.log(outputManage)
      let options = {}
      options = {
        scriptPath: join(process.cwd(), '/python_scripts'), // process.cwd()：读取 当前nodejs程序的根目录
        pythonPath: join(process.cwd(), '/python-3.10.10-embed-win32/python'),
        // pythonOptions: ['-u'], // get print results in real-time
        args: [
          `-filePath=${JSON.stringify(files)}`,
          `-outputManage=${JSON.stringify(outputManage)}`
        ],
        mode: 'text'
      }

      PythonShell.run('excelToPdf.py', options)
        .then((result) => {
          console.log('result---: ', result.toString())
          const resultArr = result.toString().split(',')
          console.log(resultArr)
          const returnArr: { fileId: string; success: boolean }[] = []
          resultArr.map((item) => {
            returnArr.push({
              fileId: item,
              success: true
            })
          })
          pResolve(returnArr)
        })
        .catch((error) => console.log(error))
    })
  })
}
/** 从pdf中提取资源 */
const extractResources = (store) => {
  return ipcMain.handle('handle:extractResources', (_event, files = []) => {
    // console.log(files)
    return new Promise(async (pResolve) => {
      const outputManage = store.get('outputManage')
      console.log(outputManage)
      let options = {}
      options = {
        scriptPath: join(process.cwd(), '/python_scripts'), // process.cwd()：读取 当前nodejs程序的根目录
        pythonPath: join(process.cwd(), '/python-3.10.10-embed-win32/python'),
        // pythonOptions: ['-u'], // get print results in real-time
        args: [
          `-filePath=${JSON.stringify(files)}`,
          `-outputManage=${JSON.stringify(outputManage)}`
        ],
        mode: 'text'
      }

      PythonShell.run('extractImages.py', options)
        .then((result) => {
          console.log('result---: ', result.toString())
          const resultArr = result.toString().split(',')
          console.log(resultArr)
          const returnArr: { fileId: string; success: boolean }[] = []
          resultArr.map((item) => {
            returnArr.push({
              fileId: item,
              success: true
            })
          })
          pResolve(returnArr)
        })
        .catch((error) => console.log(error))
    })
  })
}
/** 从pdf中提取资源 */
const compress = (store) => {
  return ipcMain.handle('handle:compress', (_event, files = []) => {
    // console.log(files)
    return new Promise(async (pResolve) => {
      const outputManage = store.get('outputManage')
      console.log(outputManage)
      let options = {}
      options = {
        scriptPath: join(process.cwd(), '/python_scripts'), // process.cwd()：读取 当前nodejs程序的根目录
        pythonPath: join(process.cwd(), '/python-3.10.10-embed-win32/python'),
        // pythonOptions: ['-u'], // get print results in real-time
        args: [
          `-filePath=${JSON.stringify(files)}`,
          `-outputManage=${JSON.stringify(outputManage)}`
        ],
        mode: 'text'
      }

      PythonShell.run('compress.py', options)
        .then((result) => {
          console.log('result---: ', result.toString())
          const resultArr = result.toString().split(',')
          console.log(resultArr)
          const returnArr: { fileId: string; success: boolean }[] = []
          resultArr.map((item) => {
            returnArr.push({
              fileId: item,
              success: true
            })
          })
          pResolve(returnArr)
        })
        .catch((error) => console.log(error))
    })
  })
}
/** 根据path，返回对应的文件流 */
const getFileStreamByPath = () => {
  return ipcMain.handle('file:getFileStreamByPath', async (event, values = {}) => { 
    console.log(event, values)
  })
}

export {
  openDirectory,
  getStoreValue,
  setStoreValue,
  setStoreValues,
  deleteStoreValue,
  deleteAllStoreValue,
  hasStoreValue,
  setTitle,
  chooseFiles,
  pdfToImg,
  pdfToWord,
  pptToPdf,
  wordToPdf,
  excelToPdf,
  extractResources,
  getFileStreamByPath,
  compress
}
